package models;

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import controllers.Security;
import exceptions.DuplicateUrlKeyException;

import play.Play;
import play.data.validation.Required;
import play.db.jpa.JPABase;
import play.db.jpa.Model;

/**
 * 产品类别
 * 
 * @author popoer
 *
 */
@Entity
@Table(name="product_type")
public class ProductType extends Model {
	
	@ManyToOne
	public ProductType parent;
	
	@Required
	@Column(name="name")
	public String name;
	
	public String image;
		
//	@ManyToMany
//	@JoinTable(name="product_2_type",
//			joinColumns={@JoinColumn(name="product_type_id",referencedColumnName="id")},
//			inverseJoinColumns={@JoinColumn(name="product_id",referencedColumnName="id")})
	
	public transient List<Product> products;

	@OneToMany(mappedBy="parent",cascade=CascadeType.DETACH)
	public List<ProductType> children;
	
	public int priority;
	
	@Column(name="url_key",unique=true,nullable=false)
	public String urlKey;
	
	@Column(name="create_time")
	public Date createTime = new Date();
	
	@Column(name="update_time")
	public Date updateTime = new Date();
	
	@ManyToOne
	public User creator = new User();
	
	@ManyToOne
	public User modifier = new User();
	
	public static List<ProductType> list(Long parentId){
		if(parentId==null){
			return ProductType.find("from ProductType where parent is null order by priority").fetch();
		}
		return ProductType.find("from ProductType where parent.id=? order by priority", parentId).fetch();
	}
	
	@Override
	public String toString() {
		return this.name;
	}
	
	public static long getRootId(){
		String rootId = Play.configuration.getProperty("producttype.root.id");
		return Long.parseLong(rootId);
	}

	public static ProductType findByUrlKey(String urlKey){
		return ProductType.find("from ProductType where urlKey=?", urlKey).first();
	}

	@Override
	public void _save() {
		ProductType productType;
		if(this.id==null){
			productType = findByUrlKey(this.urlKey);
		}else{
			productType = find("from ProductType where urlKey=? and id<>?", this.urlKey,this.id).first();
		}
		if(productType!=null){
			throw new DuplicateUrlKeyException();
		}
		
		if(this.creator!=null){
			this.creator = User.findByUsername(this.creator.username);
		}
		if(this.modifier!=null){
			this.modifier = User.findByUsername(this.modifier.username);
		}
		this.updateTime=new Date();
		super._save();
	}
}
